package com.stx.jeepay.manager.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stx.jeepay.core.aop.MethodLog;
import com.stx.jeepay.core.entity.SysLogEntity;
import com.stx.jeepay.core.enums.ApiCodeEnum;
import com.stx.jeepay.core.model.ApiPageRes;
import com.stx.jeepay.core.model.ApiRes;
import com.stx.jeepay.core.service.SysLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "系统管理（系统日志）")
@RestController
@RequestMapping("api/sysLog")
public class SysLogController extends CommonCtrl {
    @Autowired
    private SysLogService sysLogService;

    @ApiOperation("系统日志分页信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "pageNumber", value = "分页页码", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "分页条数", dataType = "int", defaultValue = "20"),
            @ApiImplicitParam(name = "createdStart", value = "日期格式字符串（yyyy-MM-dd HH:mm:ss），时间范围查询--开始时间，查询范围：大于等于此时间"),
            @ApiImplicitParam(name = "createdEnd", value = "日期格式字符串（yyyy-MM-dd HH:mm:ss），时间范围查询--结束时间，查询范围：小于等于此时间"),
            @ApiImplicitParam(name = "userId", value = "系统用户ID"),
            @ApiImplicitParam(name = "userName", value = "用户姓名"),
            @ApiImplicitParam(name = "sysType", value = "所属系统： MGR-运营平台, MCH-商户中心")
    })
    @PreAuthorize("hasAuthority('ENT_LOG_LIST')")
    @GetMapping("")
    public ApiPageRes<SysLogEntity> list() {
        SysLogEntity sysLog = getObject(SysLogEntity.class);
        JSONObject paramJSON = getReqParamJSON();
        LambdaQueryWrapper<SysLogEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (sysLog.getUserId() != null) {
            queryWrapper.eq(SysLogEntity::getUserId, sysLog.getUserId());
        }
        if (StringUtils.isNotBlank(sysLog.getUserName())) {
            queryWrapper.eq(SysLogEntity::getUserName, sysLog.getUserName());
        }
        if (StringUtils.isNotEmpty(sysLog.getSysType())) {
            queryWrapper.eq(SysLogEntity::getSysType, sysLog.getSysType());
        }
        if (paramJSON != null) {
            if (StringUtils.isNotEmpty(paramJSON.getString("createdStart"))) {
                queryWrapper.ge(SysLogEntity::getCreatedAt, paramJSON.getString("createdStart"));
            }
            if (StringUtils.isNotEmpty(paramJSON.getString("createdEnd"))){
                queryWrapper.le(SysLogEntity::getCreatedAt,paramJSON.getString("createdEnd"));
            }
        }
        queryWrapper.orderByDesc(SysLogEntity::getCreatedAt);
        IPage<SysLogEntity> pages = sysLogService.page(getIPage(), queryWrapper);
        return ApiPageRes.pages(pages);
    }

    @ApiOperation("查看日志详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "sysLogId", value = "系统日志ID", required = true)
    })
    @PreAuthorize("hasAuthority('ENT_SYS_LOG_VIEW')")
    @GetMapping("/{sysLogId}")
    public ApiRes detail(@PathVariable("sysLogId") String sysLogId){
        SysLogEntity sysLog = sysLogService.getById(sysLogId);
        if (sysLog==null){
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_SELETE);
        }
        return ApiRes.ok(sysLog);
    }

    @ApiOperation("删除日志")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "iToken", value = "用户身份凭证", required = true, paramType = "header"),
            @ApiImplicitParam(name = "selectedIds", value = "系统日志ID（若干个ID用英文逗号拼接）", required = true)
    })
    @PreAuthorize("hasAuthority('ENT_SYS_LOG_DEL')")
    @MethodLog(remark = "删除日志信息")
    @DeleteMapping("/{selectedIds}")
    public ApiRes delete(@PathVariable("selectedIds") String selectedIds){
        List<String> idsList = StrUtil.split(selectedIds, ",");
        boolean result = sysLogService.removeByIds(idsList);
        if (!result){
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_DELETE);
        }
        return ApiRes.ok();
    }
}
